//
//  AddressManagerViewController.m
//  PPDL
//
//  Created by 王洋 on 2019/7/24.
//  Copyright © 2019 王洋. All rights reserved.
//

#import "AddressCell.h"
#import "AddressManagerViewController.h"
#import "AddAddressViewController.h"

@interface AddressManagerViewController () <UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableview;
@property (weak, nonatomic) IBOutlet UIButton *addAddressBtn;

@property (nonatomic, strong) NSMutableArray <AddressItemModel *> *addressArray;

@end

@implementation AddressManagerViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    [self request_AddressList];
    //在这里面刷新数据
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
}

- (void)request_AddressList {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_ADDRESS_LIST];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        if ([data isKindOfClass:[NSDictionary class]]) {
            
            NSString * code = [data valueForKey:@"code"];
            if ([code isEqualToString:@"200"]) {
                NSArray *resultArray = [data valueForKey:@"data"];
                if ([resultArray isKindOfClass:[NSArray class]]) {
                    
                    if (resultArray.count > 0) {
                        [self.addressArray removeAllObjects];
                        [[TTNoResultManager shareManager] hideNoResultWithView:self.tableview];
                    }
                    
                    if (resultArray.count == 0) {
                        
                        [[TTNoResultManager shareManager] showNoResultWithStateInView:self.tableview errorCode:kTTViewStateAddressEmpty btnTitle:@"" didPressButton:^{
                            
                        }];
                    }
                    
                    for (int i = 0; i< resultArray.count; i++) {
                        NSDictionary *addressDic = [resultArray objectAtIndex:i];
                        AddressItemModel *model = [[AddressItemModel alloc] init];
                        model.addressID = [addressDic valueForKey:@"id"];
                        model.addressName = [addressDic valueForKey:@"name"];
                        model.addressPhone = [addressDic valueForKey:@"phone"];
                        model.provence = [addressDic valueForKey:@"province"];
                        model.city = [addressDic valueForKey:@"city"];
                        model.area = [addressDic valueForKey:@"area"];
                        model.addressDesc = [addressDic valueForKey:@"address"];
                        model.isDefault = [[addressDic valueForKey:@"isUse"] boolValue];
                        [self.addressArray addObject:model];
                    }
                    
                    
                    
                    [self.tableview reloadData];
                } else {
                    [SVProgressHUD showErrorWithStatus:[data valueForKey:@"msg"]];
                    [SVProgressHUD dismissWithDelay:1];
                }
            } else {
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"msg"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        } else {
            
        }
    } FailedBlock:^(NSError * _Nonnull error) {
        
    }];
}

- (void)request_AddressUpdateWithType:(ETTAddressActionType)type AndModel:(AddressItemModel *)model {

    NSMutableDictionary *dic = @{}.mutableCopy;
    
    switch (type) {
        case ETTAddressActionType_Edit:{
            
        
           } break;
        case ETTAddressActionType_Delete:{
            
            [dic setValue:@"1" forKey:@"isDel"];

        } break;
        case ETTAddressActionType_SetDefault:{
            
            [dic setValue:@"1" forKey:@"isUse"];

        } break;
            
        default:
            break;
    }
    
    [dic setValue:model.addressID forKey:@"id"];
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_ADDRESS_UPDATE];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        if ([data isKindOfClass:[NSDictionary class]]) {
            
            NSString * code = [data valueForKey:@"code"];
            if ([code isEqualToString:@"200"]) {
                
                    [self request_AddressList];

            } else {
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"msg"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        } else {
            
        }
    } FailedBlock:^(NSError * _Nonnull error) {
        
    }];
}

- (void)initView {
    
    self.title = @"收货地址";

    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    
    self.tableview.estimatedSectionHeaderHeight = 0;
    self.tableview.estimatedSectionFooterHeight = 0;
    self.tableview.estimatedRowHeight = 0;
    
    self.tableview.backgroundColor = PP_Default_Color_Gray_F1F1F1;
    [self.tableview registerNib:[UINib nibWithNibName:@"AddressCell" bundle:nil] forCellReuseIdentifier:@"AddressCellID"];
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
}

- (IBAction)AddAddress:(id)sender {
    
    [self.navigationController pushViewController:[AddAddressViewController new] animated:YES];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    AddressCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AddressCellID" forIndexPath:indexPath];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;

    [cell fillCellWithModel:self.addressArray[indexPath.row]];
    
    WEAKSELF
    cell.editBtnClickBlock = ^(AddressItemModel * _Nonnull model) {
    
        //当前模型带入下一个vc以修改
        AddAddressViewController *addressEdit = [AddAddressViewController new];
        addressEdit.defaultModel = model;
        [weakSelf.navigationController pushViewController:addressEdit animated:YES];
    };
    
    //在cell更新状态后同时更新数据源
    cell.refreshItemModel = ^(AddressItemModel * _Nonnull model) {
        
        [self request_AddressUpdateWithType:ETTAddressActionType_SetDefault AndModel:model];
        
//        [self alert:[NSString stringWithFormat:@"收件人姓名：%@\n收件人手机号：%@\n已设为默认收货地址",model.addressName,model.addressPhone]];
    };
    
    cell.deleteBtnClickBlock = ^(AddressItemModel * _Nonnull model) {
        
        [weakSelf alert:@"是否确认删除当前地址" leftTitle:@"取消" Action:^(UIAlertAction * _Nonnull action) {
            
        } rightTitle:@"确认" Action:^(UIAlertAction * _Nonnull action) {
            
            [self request_AddressUpdateWithType:ETTAddressActionType_Delete AndModel:model];
            
            if (weakSelf.addressArray.count == 0) {
                
                [[TTNoResultManager shareManager] showNoResultWithStateInView:self.tableview errorCode:kTTViewStateAddressEmpty btnTitle:@"" didPressButton:^{
                    
                }];
            }
        }];
    };

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.changeAddress) {
        self.changeAddress(self.addressArray[indexPath.row]);
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.addressArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 120;
}

- (NSMutableArray<AddressItemModel *> *)addressArray {
    if (!_addressArray) {
        _addressArray = @[].mutableCopy;
    }
    return _addressArray;
}

@end
